import { defineStore } from "pinia";
import { store } from "@/store";
import { routerArrays } from "@/layout/types";
import { router, resetRouter } from "@/router";
import { storageLocal } from "@pureadmin/utils";
import { getLogin, getUerInfo, type User } from "@/api/user";
import type { UserResult } from "@/api/user";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import { setToken, removeToken, userKey } from "@/utils/auth";
export const useUserStore = defineStore({
  id: "pure-user",
  state: (): User => ({
    authorities: [],
    dataScopes: [],
    roles: [],
    user: null
  }),
  actions: {
    async loginGetUserInfo() {
      return new Promise<User>(async resolve => {
        const userInfo = await getUerInfo();
        storageLocal().setItem(userKey, userInfo);
        const { authorities, dataScopes, roles, user } = userInfo;
        this.authorities = authorities;
        this.dataScopes = dataScopes;
        this.roles = roles;
        this.user = user;
        resolve(userInfo);
      });
    },
    /** 登入 */
    async loginByUsername(data) {
      return new Promise<UserResult>((resolve, reject) => {
        getLogin(data)
          .then(async udata => {
            if (udata) {
              udata.token && setToken(udata);
              udata.token && (await this.loginGetUserInfo());
              resolve(udata);
            } else {
              reject(null);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /** 前端登出（不调用接口） */
    logOut() {
      this.username = "";
      this.roles = [];
      removeToken();
      useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
      resetRouter();
      router.push("/login");
    }
  }
});

export function useUserStoreHook() {
  return useUserStore(store);
}
